package cn.itcast.bos.web.action.base;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.service.base.CourierService;

@Actions
@Namespace("/")
@ParentPackage("struts-default")

@Controller
@Scope("prototype")
public class CourierAction extends ActionSupport implements ModelDriven<Courier> {

	@Autowired
	private CourierService courierService;

	private Courier c = new Courier();

	@Override
	public Courier getModel() {
		return c;
	}

	// 转发地址栏路径没改变，html中使用相对路径无法加载到js和css
	@Action(value = "courier_save", results = {
			@Result(name = "success", type = "redirect", location = "/pages/base/courier.html") })
	public String save() {
		courierService.save(c);
		return SUCCESS;
	}

	// 属性驱动
	private int page;
	private int rows;

	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	// 分页列表查询
	@Action(value = "courier_pageQuery")
	public void pageQuery() {
		Pageable pageable = new PageRequest(page - 1, rows);
		// 封装查询条件

		Specification<Courier> specification = new Specification<Courier>() {

			@Override
			/**
			 * 构造条件查询方法，如果方法返回null，代表无条件查询。 Root 参数 获取条件表达式 name=? age =?
			 * CriteriaQuery 参数，构造简单查询条件返回 提供where 方法 CriteriaBuilder 参数 构造
			 * Predicate对象，条件对象，构造复杂查询效果
			 */
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				//
				
				List<Predicate> list = new ArrayList<Predicate>();
				// 当前查询 Root 根对象 Courier
				// 单表查询（查询当前对象 对应 数据表）
				if (StringUtils.isNotBlank(c.getCourierNum())) {
					// courierNum = ?
					Path<Object> path = root.get("courierNum");
					/*System.out.println("getParentPath"+ path.getParentPath());
					System.out.println("Model" + path.getModel());
					System.out.println("as" + path.as(String.class));*/
					
					Predicate p1 = cb.equal(root.get("courierNum").as(String.class), c.getCourierNum());
					list.add(p1);
				}
				if (StringUtils.isNotBlank(c.getCompany())) {
					// company like '%%';
					Predicate p2 = cb.like(root.get("company").as(String.class), "%" + c.getCompany() + "%");
					list.add(p2);
				}
				if (StringUtils.isNotBlank(c.getType())) {
					// type = ?
					Predicate p3 = cb.equal(root.get("type").as(String.class), c.getType());
					list.add(p3);
				}
					
				// 多表查询（查询当前对象 关联对象 对应数据表）
				// 使用Courier(Root),关联Standard
				if (c.getStandard() != null && StringUtils.isNotBlank(c.getStandard().getName())) {
					Join<Object, Object> standardRoot = root.join("standard", JoinType.INNER);
					// 进行 收派标准 名称 模糊查询
					Predicate p4 = cb.like(standardRoot.get("name").as(String.class),
							"%" + c.getStandard().getName() + "%");
					list.add(p4);

				}
				//最后把所有条件用and拼接起来
				Predicate p = cb.and(list.toArray(new Predicate[0]));
				return p;
			}
		};

		Page<Courier> pageData = courierService.findPageData(specification, pageable);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", pageData.getTotalPages());
		result.put("rows", pageData.getContent());
		//WriteMapNullValue——–是否输出值为null的字段,默认为false 
		String jsonString = JSONObject.toJSONString(result ,SerializerFeature.WriteMapNullValue);
		System.out.println(jsonString);
		try {
			ServletActionContext.getResponse().setCharacterEncoding("utf-8");
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String ids;
	
	public void setIds(String ids) {
		this.ids = ids;
	}

	@Action(value = "courier_delBatch", results = {
			@Result(name = "success", type = "redirect", location = "/pages/base/courier.html") })
	public String delBatch() {
		String[] idArray = ids.split(",");
		
		courierService.delBatch(idArray);
		return SUCCESS;
	}
	
	@Action(value = "courier_restoreBatch", results = {
			@Result(name = "success", type = "redirect", location = "/pages/base/courier.html") })
	public String restoreBatch() {
		String[] idArray = ids.split(",");
		
		courierService.restoreBatch(idArray);
		return SUCCESS;
	}

}
